import { Button, Cascader, Form, Input, Select, message } from 'antd'
import React, { useEffect, useState } from 'react'
import { observer } from 'mobx-react-lite'

import Upload from '@/components/upload'
import { storeAll } from '@/store'
import { layout, tailLayout } from '@/utils/contants'
import './style.scss'
import { addCarsRequest } from '@/apis/cars'
import { carNumberRule } from '@/utils/formRules'

const AddCars: React.FC = () => {
	const [pic, setPic] = useState<string>('')
	const [form] = Form.useForm()
	const { parkingStore: { options, parking, setOptions, getParkingLot }, usersStore: { userOptions }, carsStore: { getCars } } = storeAll

	useEffect(() => {
		setOptions(parking, 0)
	}, [parking, setOptions])

	const getImgUrl = (url: string) => {
		setPic(url)
	}

	const onFinish = (value: any) => {
		if (!pic) return
		value.picture = pic
		value.pid = value.pid[2]
		addCarsRequest(value).then((res: any) => {
			message.success(res.message)
			form.resetFields()
			setPic('')
			getParkingLot(0)
			getCars()
		})
	}

	return <div className="addCarsWrap">
		<Form form={form} {...layout} onFinish={onFinish}>
			<Form.Item label="用户" name="uid" rules={[{ required: true }]}>
				<Select options={userOptions}></Select>
			</Form.Item>
			<Form.Item label="车牌号" name="number" rules={[carNumberRule]}>
				<Input />
			</Form.Item>
			<Form.Item label="位置" name="pid" rules={[{ required: true }]}>
				<Cascader options={options}></Cascader>
			</Form.Item>
			<Form.Item label="图片" name="picture">
				<Upload getImgUrl={getImgUrl} src={pic}></Upload>
			</Form.Item>
			<Form.Item {...tailLayout}>
				<Button type="primary" htmlType="submit">
					添加
				</Button>
				<Button htmlType="button" onClick={() => form.resetFields()}>
					重置
				</Button>
			</Form.Item>
		</Form>
	</div>
}

export default observer(AddCars)